package com.youlai.system.Task;


import com.youlai.system.model.entity.DeviceConfig;
import com.youlai.system.plugin.opcua.OpcUaHelper;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class main {


    // 线程池配置
    private static ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(16);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(10);
        executor.setThreadNamePrefix("MyTaskExecutor-");
        executor.initialize();
        return executor;
    }

    // 任务创建方法
    private static Runnable createConnectionTask(DeviceConfig deviceConfig, CountDownLatch latch, List<String> nodeIds) {
        return () -> {
            if (!deviceConfig.getConnected()) {
                String ip = deviceConfig.getIp();
                try {

                    OpcUaHelper opcUaHelper = new OpcUaHelper();
                    opcUaHelper.Connect(ip,4840);
                    deviceConfig.setConnected(true); // 设置连接状态为成功

                    //开始订阅
                    opcUaHelper.StartSubscription(deviceConfig, nodeIds, new ManagedDataItem.DataValueListener() {
                        @Override
                        public void onDataValueReceived(ManagedDataItem managedDataItem, DataValue dataValue) {
                            System.out.println("dataValue = " + dataValue);
                        }
                    });

                } catch (Exception e) {
                    System.err.println("Failed to connect to " + ip + ": " + e.getMessage());
                    deviceConfig.setConnected(false); // 设置连接状态为失败
                } finally {
                    System.out.println(ip + " Connect Finish...." + (deviceConfig.getConnected() ? " Success" : " Failed"));
                    latch.countDown(); // 任务完成，计数器减一
                }
            } else {
                System.out.println(deviceConfig.getIp() + " is not configured to connect.");
                latch.countDown(); // 任务完成，计数器减一
            }
        };
    }



    public static void main(String[] args) {
        OpcUaHelperTest opcUaHelperTest = new OpcUaHelperTest();

        // 全局IP配置列表
//        List<IpConfig> ipConfigs = new ArrayList<>();
//        ipConfigs.add(new IpConfig("192.168.0.1", true));
//        ipConfigs.add(new IpConfig("192.168.0.2", true));
//        ipConfigs.add(new IpConfig("192.168.0.3", false)); // 不连接

        List<DeviceConfig> deviceConfigList = new ArrayList<>();

        deviceConfigList.add(new DeviceConfig(
                1L,
                "192.168.0.1",
                4840,
                "PLC_1",
                1,
                1,
                false,
                false,
                true,
                "1,1",
                "2024-05-06 17:15",
                "TestPLC"));
        deviceConfigList.add(new DeviceConfig(
                2L,
                "192.168.0.2",
                4840,
                "PLC_2",
                1,
                1,
                false,
                false,
                true,
                "1,1",
                "2024-05-06 17:15",
                "TestPLC"));

        OpcUaHelper opcUaHelper = new OpcUaHelper();
        List<String> nodeItems = new ArrayList<>();
        nodeItems.add("DBLine.Real1");
        nodeItems.add("DBLine.Real2");
        nodeItems.add("DBLine.Real3");
        List<String> str = opcUaHelper.FormatNodeIds(nodeItems);

        // 创建线程池
        ThreadPoolTaskExecutor executor = taskExecutor();

        // 创建 CountDownLatch
        CountDownLatch latch = new CountDownLatch(deviceConfigList.size());

        // 提交任务到线程池
        for (DeviceConfig deviceConfig : deviceConfigList) {
            executor.execute(createConnectionTask(deviceConfig,  latch, str));
        }

        // 打印最终的连接状态
        for (DeviceConfig deviceConfig : deviceConfigList) {
            System.out.println("IP: " + deviceConfig.getIp() + " - Connected: " + deviceConfig.getConnected());
        }
    }

}
